<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateInvoicesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('invoices', function (Blueprint $table) {
            $table->unsignedBigInteger('id')->primary()->comment('发票ID(雪花ID)');
            $table->string('invoice_number', 50)->unique()->comment('发票申请单号');
            $table->unsignedBigInteger('tenant_id')->comment('租户ID');
            $table->unsignedBigInteger('landing_company_id')->comment('落地公司ID');
            $table->decimal('invoice_amount', 15, 2)->comment('开票金额');
            $table->enum('billing_type', ['6_regular', '6_special', 'differential_regular'])->comment('开票类型：6%普票、6%专票、差额普票');
            $table->string('billing_category', 100)->comment('开票类目');
            $table->string('invoice_title', 200)->comment('发票抬头');
            $table->string('tax_number', 50)->comment('纳税人识别号');
            $table->string('company_address', 500)->nullable()->comment('公司地址');
            $table->string('company_phone', 20)->nullable()->comment('公司电话');
            $table->string('bank_name', 200)->nullable()->comment('开户银行');
            $table->string('bank_account', 100)->nullable()->comment('银行账号');
            $table->text('invoice_content')->comment('发票内容');
            $table->text('related_tasks')->nullable()->comment('关联任务');
            $table->string('invoice_file_path', 500)->nullable()->comment('发票文件COS路径');
            $table->string('status', 20)->default('新建')->comment('开票状态：新建、开票中、已拒绝、已开票、已作废');
            $table->text('rejection_reason')->nullable()->comment('拒绝原因');
            $table->string('express_tracking_number', 100)->nullable()->comment('快递单号');
            $table->text('invoice_remarks')->nullable()->comment('开票备注');
            $table->datetime('application_time')->comment('申请时间');
            $table->datetime('processed_at')->nullable()->comment('处理时间');
            $table->datetime('issued_at')->nullable()->comment('开票时间');
            $table->unsignedBigInteger('created_by')->nullable()->comment('申请人ID');
            $table->unsignedBigInteger('processed_by')->nullable()->comment('处理人ID');
            $table->timestamps();
            
            // 外键和索引
            $table->foreign('tenant_id')->references('id')->on('tenants')->onDelete('cascade');
            $table->foreign('landing_company_id')->references('id')->on('landing_companies')->onDelete('cascade');
            $table->index(['tenant_id', 'status']);
            $table->index(['application_time']);
            $table->index(['billing_type']);
            $table->index(['landing_company_id']);
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('invoices');
    }
}
